import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-user-page',
	templateUrl: './user-page.component.html',
	styleUrls: ['./user-page.component.css']
})
export class UserPageComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			userName: {
				validators: {
					notEmpty: {
						message: '请输入账户名'
					},
					stringLength: {
						max: 30,
						message: '账户名30字以内'
					},
					callback: {
						callback: function (value, validator, $field) {
							if (value) {
								var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
								if (reg.test(value)) {
									return {
										valid: false,
										message: '请注册英文账号'
									}
								} else {
									return true;
								}
							} else {
								return true;
							}
						}.bind(this)
					},
					remote: {
						message: '账户名已存在',
						url: config.BaseURL + "user/withoutAuth/validateUserName.html",
					}
				}
			},
			password: {
				validators: {
					notEmpty: {
						message: '请输入密码'
					},
					stringLength: {
						min: 6,
						message: '密码不少于6位'
					},
					callback: {
						callback: function (value, validator, $field) {
							if (this.page.repassword) {
								if (value === this.page.repassword) {
									return true;
								} else {
									return {
										valid: false,
										message: '和确认密码不一致'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			repassword: {
				validators: {
					notEmpty: {
						message: '请输入确认密码'
					},
					identical: {
						field: 'password',
						message: '两次密码不一致'
					},
				}
			},
			outsourcingTeamName: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择实施团队'
					}
				}
			},
			workerType: {
				trigger: 'change',
				validators: {
					notEmpty: {
						message: '请选择员工类型'
					}
				}
			},
			name: {
				validators: {
					notEmpty: {
						message: '请输入真实姓名'
					},
					stringLength: {
						max: 30,
						message: '姓名30字以内'
					},
				}
			},
			phone: {
				validators: {
					notEmpty: {
						message: '请输入电话号码'
					},
					integer: {
						message: '请输入数字电话号码'
					}
				}
			},
			workerState: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择在职状态'
					}
				}
			},
			baseWages: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '基本薪资[元/月]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '基本薪资[元/月]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			tallSubsidy: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '高精度17-4补贴[[元/通道]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '高精度17-4补贴[[元/通道]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			royalty: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '安装提成[元/台]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '安装提成[元/台]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			subsidy: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '17-4(V1)补贴[元/通道]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '17-4(V1)补贴[元/通道]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			}
		}

	}

	page: any = {
		userName: '',
		password: '',
		repassword: '',
		name: '',
		description: '',
		phone: '',
		email: '',
		workerType: '',
		outsourcingTeamId: '',
		outsourcingTeamName: '',
		companyName: '',
		workerState: '',
		baseWages: '',
		tallSubsidy: '',
		royalty: '',
		subsidy:''
	}
	page_title: string = '新增';
	pageType: string = 'new';
	userId = null;
	submitted: boolean = false;
	curPage: number = 0; //缓存页码

	workerTypeEm = [
		{
			value: 0,
			label: '管理员'
		  },
		  {
			value: 1,
			label: '正式员工'
		  },
		  {
			value: 2,
			label: '兼职员工'
		  },
		  {
			value: 3,
			label: '外包员工'
		  }
	]
	workerTypeList = this.workerTypeEm

	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.userId = queryParams.id;
			this.pageType = queryParams.type;
			this.curPage = queryParams.nowPage;
		});
	}
	//表单提交
	onSubmit() {
		if (!this.page.outsourcingTeamId) {
			this.jsonApiService.message('请选择实施团队');
			return;
		}
		$('#userForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#userForm').data('bootstrapValidator').isValid(); //验证是否通过
		if (isValid) {
			const page : Record<string,any>= this.deepClone(this.page)
			page.baseWages= this.dollarToCent(page.baseWages)
			page.tallSubsidy= this.dollarToCent(page.tallSubsidy)
			page.royalty= this.dollarToCent(page.royalty)
			page.subsidy= this.dollarToCent(page.subsidy)

			var reqdata = new FormData();
			var url;
			if (this.pageType === "new") {
				page.companyName = '项目实施'
				url = 'user/addOutsourcingUser.html';
				for (let item in page) {
					if(page[item]){
						reqdata.append(item, page[item]);
					}
				}
			} else if (this.pageType === "updata") {
				url = 'user/updateOutsourcingUser.html';
				for (let item in page) {
					if (item === 'password' || item === 'repassword') {
						continue;
					}
					if(page[item]){
						reqdata.append(item, page[item]);
					}
				}
				reqdata.append('id', this.userId);
			}
			this.jsonApiService.form_http(url, reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.router.navigate(['/device-management/outsource-user'], {
						queryParams: {
							nowPage: this.curPage
						}
					});
				}
			})
		}
	}
	//返回资源列表页
	goBack() {
		this.router.navigate(['/device-management/outsource-user'], { queryParams: { nowPage: this.curPage } });
	}
	ngOnInit() {
		var that = this;
		this.getSalaryTemplate() //获取薪酬模板列表
		that.initAllTeam().then(() => {
			that.select2Team().then(() => {
				that.load()
			})
		})
	}

	load() {
		const that = this
		if (that.pageType === 'updata') {
			$('#userForm').bootstrapValidator('removeField', 'password')
			$('#userForm').bootstrapValidator('removeField', 'repassword')
			that.page_title = '编辑';
			let reqdata = 'id=' + that.userId;
			that.jsonApiService.http("user/userInfo.html", reqdata).subscribe(data => {
				if (data.success) {
					for (let item in that.page) {
						if (data.data[item]) {
							that.page[item] = data.data[item];
						}
					}
					if (data.data.workerType == null) {
						that.page.workerType = ''
					} else {
						that.page.workerType = data.data.workerType;
					}

					if (data.data.workerState == null) {
						that.page.workerState = ''
					} else {
						that.page.workerState = data.data.workerState;
					}

					let outsourcingTeamName = ''
					if (data.data.outsourcingTeamId) {
						outsourcingTeamName = data.data.outsourcingTeamName
					}

					this.page.baseWages = this.centToDollar(data.data.baseWages)
					this.page.subsidy = this.centToDollar(data.data.subsidy)
					this.page.tallSubsidy = this.centToDollar(data.data.tallSubsidy)
					this.page.royalty = this.centToDollar(data.data.royalty)

					$("#teamSelect2").val(data.data.outsourcingTeamId).trigger('change');
					// 因为返回的id在选择框中筛选过了
					var str = $("<span class='select2-selection__rendere'>" + outsourcingTeamName + "</span>");
					$('#teamSelect2').val("");
					$("#select2-teamSelect2-container").empty();
					$("#select2-teamSelect2-container").attr("title", "");
					$("#select2-teamSelect2-container").prepend(str);
					$('#outsourcingTeamName').val(outsourcingTeamName).change()
				} else {
					this.jsonApiService.message(data.message);
				}
			})
		} else {
			this.page_title = '新增';
		}
		setTimeout(() => {
			$("#userForm").data('bootstrapValidator').resetForm();
		},500)
	}

	teamList: any = []
	//拉取实施团队数据
	initAllTeam() {
		var that = this;
		return new Promise(function (resolve, reject) {
			let reqdata = 'userType=1';
      that.jsonApiService.http('user/teamListByAuth.html', reqdata).subscribe(data => {
        if (data.data.length > 0) {
					var teamList = data.data;
					var selectdata = [];
					for (var i = 0; i < teamList.length; i++) {
						var obj = {
							id: teamList[i].id,
							text: teamList[i].companyName,
							userType: teamList[i].userType
						}
						selectdata[i] = obj;
					}
				}
				that.teamList = selectdata;
				resolve(true);
      })
    })
	}
	//初始化select2 实施团队配置
	select2Team() {
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
				System.import('assets/js/select2-zh-CN.js').then(() => {
					$("#teamSelect2").select2({
						language: "zh-CN",
						placeholder: "请选择",
						allowClear: true,
						data: that.teamList, //为Select添加数据
					}).on("select2:select", function (e) {
						var data = e.params.data;
						that.page.outsourcingTeamId = data.id;
						that.page.outsourcingTeamName = data.text;
						$('#outsourcingTeamName').val(data.text).change()
						$("#teamSelect2").val(data.id).trigger('change');
						$("#userForm").data('bootstrapValidator').resetForm();
						that.selectProjectTeam(data)
					});
					resolve(true);
				})
			})
		})
	}

	// 选择实施团队
	selectProjectTeam(value: Record<string,any>){
		const item = this.teamList.filter(item => {
		return item.id === value.id
		})[0]

		if (item.userType === 6) {
		// 【用户类型】为【项目实施-外包-水泥】时，员工类型枚举值有：①管理员 ②外包员工
		this.workerTypeList = this.workerTypeEm.filter(item => [0, 3].includes(item.value))
		} else if (item.userType === 5) {
		// 【用户类型】为【项目实施-兼职-水泥】时，员工类型枚举值有：①管理员 ②兼职员工
		this.workerTypeList = this.workerTypeEm.filter(item => [0, 2].includes(item.value))
		} else {
		this.workerTypeList = this.workerTypeEm
		}

		this.page.workerType = ''
	}

	// 薪酬配置弹窗
	salaryTemplateFrom: any = {
		templateName: '',
		baseWages: '',
		tallSubsidy: '',
		royalty: '',
		subsidy: ''
	}
	salaryTemplateValidatorOptions = {
		// excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			templateName: {
				validators: {
					notEmpty: {
						message: '请输入模板名称'
					},
					stringLength: {
						max: 11,
						message: '模板名称10字以内'
					}
				}
			},
			baseWages: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '基本薪资[元/月]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '基本薪资[元/月]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			tallSubsidy: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '高精度17-4补贴[[元/通道]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '高精度17-4补贴[[元/通道]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			royalty: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '安装提成[元/台]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '安装提成[元/台]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			},
			subsidy: {
				validators: {
					callback: {
						callback: function (value, validator, $field) {
							const regexp = /^(([1-9][0-9]*(\.)?[0-9]*)|(0(\.)([0-9]*))|(0))$/
							if (value) {
								if (!regexp.test(value)) {
									return {
										valid: false,
										message: '17-4(V1)补贴[元/通道]为大于0的数字'
									}
								}else if (value < 99999.99) {
									return true;
								} else {
									return {
										valid: false,
										message: '17-4(V1)补贴[元/通道]只能为小于99999.99的数字'
									}
								}
							} else {
								return true;
							}
						}.bind(this)
					}
				}
			}
		}
	}
	salaryTemplateList: any = [] //薪酬模板list
	addSalaryTemplate(modal) {
		const that = this
		if (that.salaryTemplateList.length === 10) {
			that.jsonApiService.message('薪酬模板最多限制10条');
			return
		}
		modal.show()
		setTimeout(() => {
			that.salaryTemplateFrom = {
				templateName: '',
				baseWages: '',
				tallSubsidy: '',
				royalty: '',
				subsidy: ''
			}
			$("#salaryTemplate").data('bootstrapValidator').resetForm();
		}, 200)
	}
	salaryTemplateClose(modal) {
		this.salaryTemplateFrom = {
			templateName: '',
			baseWages: '',
			tallSubsidy: '',
			royalty: '',
			subsidy: ''
		}
		$("#salaryTemplate").data('bootstrapValidator').resetForm();
		modal.hide()
	}
	salaryTemplateSubmit(modal) {
		if (this.salaryTemplateList.length === 10) {
			this.jsonApiService.message('薪酬模板最多限制10条');
			return
		}
		$('#salaryTemplate').bootstrapValidator('validate'); //开启验证
		let isValid = $('#salaryTemplate').data('bootstrapValidator').isValid(); //验证是否通过
		if (isValid) {
			const salaryTemplateFrom : Record<string,any>= this.deepClone(this.salaryTemplateFrom)
			salaryTemplateFrom.baseWages= this.dollarToCent(salaryTemplateFrom.baseWages)
			salaryTemplateFrom.tallSubsidy= this.dollarToCent(salaryTemplateFrom.tallSubsidy)
			salaryTemplateFrom.royalty= this.dollarToCent(salaryTemplateFrom.royalty)
			salaryTemplateFrom.subsidy= this.dollarToCent(salaryTemplateFrom.subsidy)

			var reqdata = new FormData();
			for (let item in salaryTemplateFrom) {
				if(salaryTemplateFrom[item]){
					reqdata.append(item, salaryTemplateFrom[item]);
				}
			}
			this.jsonApiService.form_http('wages/addTemplate.html', reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.getSalaryTemplate()
					modal.hide()
				}
			})
		}
	}
	//获取薪酬模板列表数据
	getSalaryTemplate() {
		this.jsonApiService.http("wages/templateList.html", '').subscribe(data => {
				if (data.success) {
					this.salaryTemplateList = data.data || []
				} else {
					this.jsonApiService.message(data.message);
				}
		})
	}
	submitPay(index) {
		const payItem = this.salaryTemplateList[index]
		this.page.baseWages = this.centToDollar(payItem.baseWages)
		this.page.subsidy = this.centToDollar(payItem.subsidy)
		this.page.tallSubsidy = this.centToDollar(payItem.tallSubsidy)
		this.page.royalty = this.centToDollar(payItem.royalty)
	}
	deletePay(index) {
		let reqdata = 'id=' + this.salaryTemplateList[index].id;
		this.jsonApiService.http("wages/deleteTemplate.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.getSalaryTemplate();
			}
		})
	}
	//深拷贝浅拷贝
	deepClone(obj) {
		let objClone = Array.isArray(obj) ? [] : {};
		if (obj && typeof obj === "object") {
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					//判断ojb子元素是否为对象，如果是，递归复制
					if (obj[key] && typeof obj[key] === "object") {
						objClone[key] = this.deepClone(obj[key]);
					} else {
						//如果不是，简单复制
						objClone[key] = obj[key];
					}
				}
			}
		}
		return objClone;
	}

	// 元转分
	dollarToCent (value: string | number | null) {
		return value ? parseInt(String( Number(value) * 100) ) : null
	}
	// 分转元
	centToDollar (value: string | number | null) {
		return value ? Number(value) / 100 : null
	}
}